﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ERPStudio;
using System.Diagnostics;
using System.Data.SqlClient;
using System.Threading;
using System.Reflection;

namespace ESRP
{
    public partial class ArhConturiRezumatFrm : FrmRezumat
    {
        const String txtToateConturile = "Toate conturile!";
        const String txtConturiUtilizate = "Conturile utilizate!";
        private String _adauga = String.Empty;
        /// <summary>
        /// contul care va fi adaugat la lansarea rezumatului
        /// </summary>
        public String AdaugaCont
        {
            get { return _adauga; }
            set { _adauga = value; }
        }
        public String FiltruDenumire = String.Empty;
        
        private String _contParinteSelectat = "N/A";
        public String ContParinteSelectat
        {
            get { return _contParinteSelectat; }
            set { _contParinteSelectat = value; }
        }

        public Int32 idxBAfiseaza = -1;
        public Int32 idxBAnterior = -1;
        public Int32 idxBUrmator = -1;
        /// <summary>
        /// categoria contului 0 - in bilant, 2 in afara bilantului
        /// </summary>
        private Int16 categorie = 0;
        private String typeCont = "A";
        /// <summary>
        /// stiva cu conturile parinte
        /// </summary>
        private Stack<String> ContParinte = new Stack<string>();
        /// <summary>
        /// stiva cu randurile anterioare care trebuie selectate
        /// </summary>
        private Stack<DataGridViewRow> m_RanduriAnteriore = new Stack<DataGridViewRow>();
        /// <summary>
        /// nivelVirtual e true daca ne aflam pe un nivel fara nici o inregistrare
        /// - de pe un asfel de nivel nu se poate merge mai in adancime
        /// </summary>
        private Boolean nivelVirtual = false;
        public ArhConturiRezumatFrm(ModuleClass mInfo,Int16 cat=0)
            : base(mInfo)
        {
            categorie = cat;
            ContParinte.Push("N/A");
            InitializeComponent();
            HandleAfterAdd += new AfterAddHandler(ConturiRezumatFrm_HandleAfterAdd);
            HandleBeforeAdd += new EventHandler(ConturiRezumatFrm_HandleBeforeAdd);
            HandleBeforeSearch += new EventHandler(ConturiRezumatFrm_HandleBeforeAdd);
            this.HandleBeforeDelAfterMessage += DocumenteFrm_HandleBeforeDelAfterMessage;


            #region Arhiva
            if (ModuleInfo.AnArhiva != String.Empty)
            {
                if(!ModuleInfo.eArhivaEditabila)
                    this.ReadOnly = true;
            }
            #endregion

            arhESRPDataSet.arhConturi.CodUnitateColumn.DefaultValue = ModuleInfo.CodUnitate;
            arhESRPDataSet.arhConturi.TerminalColumn.DefaultValue = true;
            arhESRPDataSet.arhConturi.EsteAnaliticColumn.DefaultValue = true;
            arhESRPDataSet.arhConturi.DebitInitialColumn.DefaultValue = 0;
            arhESRPDataSet.arhConturi.CreditInitialColumn.DefaultValue = 0;
            arhESRPDataSet.arhConturi.DebitPrecedentColumn.DefaultValue = 0;
            arhESRPDataSet.arhConturi.CreditPrecedentColumn.DefaultValue = 0;
            arhESRPDataSet.arhConturi.RulajCreditColumn.DefaultValue = 0;
            arhESRPDataSet.arhConturi.RulajDebitColumn.DefaultValue = 0;
            arhESRPDataSet.arhConturi.SoldColumn.DefaultValue = 0;
            ActiveControl = conturiDGV;
            EnableMainBrowseButton = false;
        }

        void ConturiRezumatFrm_HandleBeforeAdd(object sender, EventArgs e)
        {
            using (SqlConnection con = DeschideConexiune(workConnString))
            {
                AfiseazaToateConturile(con, true,true);
            }

        }

        void ConturiRezumatFrm_HandleAfterAdd(object sender, DataGridViewCellEventArgs args)
        {
            DataGridViewRow dc = conturiDGV.CurrentRow;
            if (dc == null)
                return;
            {
                Boolean isTerminal = true;
                if (dc.Cells["TerminalColumn"].Value != DBNull.Value)
                    isTerminal = Convert.ToBoolean(dc.Cells["TerminalColumn"].Value);
                if (isTerminal == false)
                {
                    conturiDGV.Rows[dc.Index].DefaultCellStyle.BackColor = Color.LightBlue;
                    conturiDGV[DebitInitialColumn.Index, dc.Index].ReadOnly = true;
                    conturiDGV[CreditInitialColumn.Index, dc.Index].ReadOnly = true;
                    conturiDGV[CreditInitialColumn.Index, dc.Index].Style.BackColor = Color.LightGray;
                    conturiDGV[DebitInitialColumn.Index, dc.Index].Style.BackColor = Color.LightGray;
                }
                else
                {
                    conturiDGV.Rows[dc.Index].DefaultCellStyle.BackColor = Color.White;
                    ///se modifica tipul contului
                    ///
                    String tip = conturiDGV[TipContColumn.Index, dc.Index].Value.ToString();
                    if (tip == "A")
                    {
                        conturiDGV[DebitInitialColumn.Index, dc.Index].ReadOnly = false;
                        conturiDGV[CreditInitialColumn.Index, dc.Index].ReadOnly = true;
                        conturiDGV[CreditInitialColumn.Index, dc.Index].Style.BackColor = Color.LightGray;
                        conturiDGV[DebitInitialColumn.Index, dc.Index].Style.BackColor = conturiDGV.Rows[dc.Index].DefaultCellStyle.BackColor;
                    }
                    if (tip == "P")
                    {
                        conturiDGV[DebitInitialColumn.Index, dc.Index].ReadOnly = true;
                        conturiDGV[CreditInitialColumn.Index, dc.Index].ReadOnly = false;
                        conturiDGV[DebitInitialColumn.Index, dc.Index].Style.BackColor = Color.LightGray;
                        conturiDGV[CreditInitialColumn.Index, dc.Index].Style.BackColor = conturiDGV.Rows[dc.Index].DefaultCellStyle.BackColor;
                    }
                    if (tip == "B")
                    {
                        conturiDGV[DebitInitialColumn.Index, dc.Index].ReadOnly = false;
                        conturiDGV[CreditInitialColumn.Index, dc.Index].ReadOnly = false;
                        conturiDGV[DebitInitialColumn.Index, dc.Index].Style.BackColor = conturiDGV.Rows[dc.Index].DefaultCellStyle.BackColor;
                        conturiDGV[CreditInitialColumn.Index, dc.Index].Style.BackColor = conturiDGV.Rows[dc.Index].DefaultCellStyle.BackColor;

                    }
                }

            }
        }

        private void ConturiRezumatFrm_Load(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            SqlConnection con = DeschideConexiune(workConnString);

            this.arhConturiTableAdapter.Connection = con;
            this.arhConturiTableAdapter.Fill(this.arhESRPDataSet.arhConturi,ModuleInfo.CodUnitate,Convert.ToInt16(ModuleInfo.AnArhiva));


            //this.conturiCorespTableAdapter.Connection = con;
            //this.conturiCorespTableAdapter.Fill(this.arhESRPDataSet.arhConturiCoresp, ModuleInfo.CodUnitate);
            this.conturiSpecialeTableAdapter.Connection = con;
            this.conturiSpecialeTableAdapter.Fill(this.eSRPDataSet.ConturiSpeciale, ModuleInfo.CodUnitate);

            #region Actualizare solduri
            /*cmd.CommandText = "balcon_UpdateSoldCont";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add(new SqlParameter("codUnitate", ModuleInfo.CodUnitate));
            cmd.ExecuteNonQuery();*/
            #endregion            

            this.tipContTableAdapter.Connection = con;
            #region Seteaza conturile care vor fi afisate, cele utilizate sau toate
            this.tipContTableAdapter.Fill(this.eSRPDataSet.TipCont);
            String DeAfisat = String.Empty;
            //if (_adauga != String.Empty) <- asa a fost pana in 26.11.2009
            if (ContParinteSelectat!="N/A")
            {
                ContParinte.Push(ContParinteSelectat);
                arhESRPDataSet.arhConturi.ContColumn.DefaultValue = _adauga;
                ///daca e un cont selectat, ordoneaza analiticele
                conturiBindingSource.Sort = "[SortValue]";
            }
            

            String afis = GetSetariLocale(con, "CUSE", "1",ModuleInfo.CodUnitate);
            if (afis == "1")
            {
                this.arhConturiTableAdapter.FillUsedCategorie(this.arhESRPDataSet.arhConturi, FiltruDenumire, ContParinte.Peek(), ((byte)categorie), ModuleInfo.CodUnitate,Convert.ToInt16(ModuleInfo.AnArhiva));
                DeAfisat = txtToateConturile;
            }
            else
            {
                this.arhConturiTableAdapter.FillByCategorieContParinte(arhESRPDataSet.arhConturi,
                    ModuleInfo.CodUnitate,
                    Convert.ToInt16(ModuleInfo.AnArhiva),
                    ((byte)categorie), ContParinte.Peek(), FiltruDenumire);
                DeAfisat = txtConturiUtilizate;
            } 
            #endregion 
            
            AddBindingSource(arhConturiBindingSource);
            AddTableAdaptor(arhConturiTableAdapter.Adapter);
            
            if (ModuleInfo.AnArhiva == String.Empty)
            {
                AddButton("Salvare[F9]", global::ERPStudio.Properties.Resources.salvare1, Salvare, ToolStripItemAlignment.Right, true);
                if (SelectionAddOn)
                    HandleSalvare += new EventHandler(Selectie);
                else
                    HandleSalvare += new EventHandler(Salvare);
            }
            else
                if(ModuleInfo.eArhivaEditabila)
                    AddButton("Salvare[F9]", global::ERPStudio.Properties.Resources.salvare1, Salvare, ToolStripItemAlignment.Right, true);

            //AddButton("Proprietati", global::ERPStudio.Properties.Resources.furl_48, ProprietatiConturi, ToolStripItemAlignment.Right, false);
            idxBAfiseaza = AddButton(DeAfisat, global::ERPStudio.Properties.Resources.rss_48, AfiseazaConturiUtilizate, ToolStripItemAlignment.Right, false);

            idxBAnterior = AddButton("Sintetic", global::ERPStudio.Properties.Resources.arrow_left_green_48, RevenireNivelAnterior, ToolStripItemAlignment.Left, false);
            idxBUrmator = AddButton("Analitice", global::ERPStudio.Properties.Resources.arrow_right_green_48, tSBNext_Click, ToolStripItemAlignment.Left, false);

            List<ToolStripMenuItem> items = new List<ToolStripMenuItem>();
            AddDropDownItem("Bilant", bilantToolStripMenuItem_Click, ref items);
            AddDropDownItem("In afara bilantului", inAfaraBilantuluiToolStripMenuItem_Click, ref items);
            AddDropDown("Categorie", global::ERPStudio.Properties.Resources.delicious_48, (EventHandler)null, items.ToArray(), ToolStripItemAlignment.Left);

 
            arhESRPDataSet.arhConturi.CategorieColumn.DefaultValue = categorie;


            #region Setare tip cont pentru adaugare
            if (ContParinteSelectat != "N/A")
            {
                SqlCommand cmd = new SqlCommand("", con);
                cmd.CommandText = "SELECT [Tip] FROM [arhConturi] WHERE [CodUnitate]=" + ModuleInfo.CodUnitate + " AND [Cont]='" + ContParinteSelectat + "'";
                cmd.CommandType = CommandType.Text;
                Object ret = cmd.ExecuteScalar();
                if (ret != null)
                {
                    
                    typeCont = ret.ToString();
                }
            }

            arhESRPDataSet.arhConturi.TipColumn.DefaultValue = typeCont; 
            #endregion
            InchideConexiune(con);
            if (ContParinte.Peek() != "N/A")
                arhESRPDataSet.arhConturi.ContColumn.DefaultValue = ContParinte.Peek() + ".";
            arhESRPDataSet.arhConturi.ContParinteColumn.DefaultValue = ContParinte.Peek();
            
            ///varinata in care porneste direct in adaugare
            if (_adauga != String.Empty)
            {
                Adauga(this, null);
                
            }
            this.SetStatusNavigationButtons();
            Setup();
            ActiveControl = conturiDGV.EditingControl;
            Cursor.Current = Cursors.Default;
        }

        private void AfiseazaToateConturile(SqlConnection con,Boolean afis,Boolean verifica)
        {
            arhConturiTableAdapter.Connection = con;
            if (verifica)
            {
                if (afis)
                {
                    if (listTSButton[idxBAfiseaza].Text == txtToateConturile)
                        arhConturiTableAdapter.FillByCategorieContParinte(arhESRPDataSet.arhConturi, ModuleInfo.CodUnitate, Convert.ToInt16(ModuleInfo.AnArhiva),((byte)categorie), ContParinte.Peek(), FiltruDenumire);
                }
                else
                {
                    if (listTSButton[idxBAfiseaza].Text == txtConturiUtilizate)
                        arhConturiTableAdapter.FillUsedCategorie(arhESRPDataSet.arhConturi, FiltruDenumire, ContParinte.Peek(), ((byte)categorie), ModuleInfo.CodUnitate, Convert.ToInt16(ModuleInfo.AnArhiva));
                }
            }
            else
            {
                if (afis)
                {
                    arhConturiTableAdapter.FillByCategorieContParinte(arhESRPDataSet.arhConturi, ModuleInfo.CodUnitate, Convert.ToInt16(ModuleInfo.AnArhiva), ((byte)categorie), ContParinte.Peek(), FiltruDenumire);
                }
                else
                {
                    arhConturiTableAdapter.FillUsedCategorie(arhESRPDataSet.arhConturi, FiltruDenumire, ContParinte.Peek(), ((byte)categorie), ModuleInfo.CodUnitate,Convert.ToInt16(ModuleInfo.AnArhiva));
                }

            }

        }

        private void AfiseazaConturiUtilizate(object sender, EventArgs e)
        {
            Salvare(this, null);
            if (EroareSalvare)
                return;
 
            try
            {
                SqlConnection con = DeschideConexiune(workConnString);
                this.tipContTableAdapter.Connection = con;
                this.tipContTableAdapter.Fill(this.eSRPDataSet.TipCont);
                if (idxBAfiseaza != -1)
                {
                    if (e == null)
                    {
                        ///nu schimba afisarile
                        if (listTSButton[idxBAfiseaza].Text != txtToateConturile)
                            AfiseazaToateConturile(con, true, false);
                        else
                            AfiseazaToateConturile(con, false, false);
                    }
                    else
                    {
                        SetSetariLocale(con, "CUSE", listTSButton[idxBAfiseaza].Text == txtToateConturile ? "0" : "1", ModuleInfo.CodUnitate);
                        ///schimba afisarile
                        if (listTSButton[idxBAfiseaza].Text == txtToateConturile)
                        {
                            AfiseazaToateConturile(con, true, true);
                            listTSButton[idxBAfiseaza].Text = txtConturiUtilizate;
                        }
                        else
                        {
                            AfiseazaToateConturile(con, false, true);
                            listTSButton[idxBAfiseaza].Text = txtToateConturile;
                        }

                    }
                }
                else
                { 
                    //tribunal
                    AfiseazaToateConturile(con, true, false);
                }
                InchideConexiune(con);
            }
            catch (System.Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
            }

        }

        private void conturiDGV_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            if (e.ListChangedType != ListChangedType.Reset || conturiDGV.Rows.Count <= 0)
                return;
            MyTrace(e.ListChangedType + "," + conturiDGV.Rows.Count.ToString());
            foreach (DataGridViewRow dc in conturiDGV.Rows)
            {
                Boolean isTerminal = true;
                if (dc.Cells["TerminalColumn"].Value!= DBNull.Value)
                    isTerminal = Convert.ToBoolean(dc.Cells["TerminalColumn"].Value);
                if (isTerminal == false)
                {
                    conturiDGV.Rows[dc.Index].DefaultCellStyle.BackColor = Color.LightBlue;
                    conturiDGV[DebitInitialColumn.Index, dc.Index].ReadOnly = true;
                    conturiDGV[CreditInitialColumn.Index, dc.Index].ReadOnly = true;
                    conturiDGV[CreditInitialColumn.Index, dc.Index].Style.BackColor = Color.LightGray;
                    conturiDGV[DebitInitialColumn.Index, dc.Index].Style.BackColor = Color.LightGray;
                }
                else
                {
                    conturiDGV.Rows[dc.Index].DefaultCellStyle.BackColor = Color.White;
                    ///se modifica tipul contului
                    ///
                    String tip = conturiDGV[TipContColumn.Index, dc.Index].Value.ToString();
                    if (tip == "A")
                    {
                        conturiDGV[DebitInitialColumn.Index, dc.Index].ReadOnly = false;
                        conturiDGV[CreditInitialColumn.Index, dc.Index].ReadOnly = true;
                        conturiDGV[CreditInitialColumn.Index, dc.Index].Style.BackColor = Color.LightGray;
                        conturiDGV[DebitInitialColumn.Index, dc.Index].Style.BackColor = conturiDGV.Rows[dc.Index].DefaultCellStyle.BackColor;
                    }
                    if (tip == "P")
                    {
                        conturiDGV[DebitInitialColumn.Index, dc.Index].ReadOnly = true;
                        conturiDGV[CreditInitialColumn.Index, dc.Index].ReadOnly = false;
                        conturiDGV[DebitInitialColumn.Index, dc.Index].Style.BackColor = Color.LightGray;
                        conturiDGV[CreditInitialColumn.Index, dc.Index].Style.BackColor = conturiDGV.Rows[dc.Index].DefaultCellStyle.BackColor;
                    }
                    if (tip == "B")
                    {
                        conturiDGV[DebitInitialColumn.Index, dc.Index].ReadOnly = false;
                        conturiDGV[CreditInitialColumn.Index, dc.Index].ReadOnly = false;
                        conturiDGV[DebitInitialColumn.Index, dc.Index].Style.BackColor = conturiDGV.Rows[dc.Index].DefaultCellStyle.BackColor;
                        conturiDGV[CreditInitialColumn.Index, dc.Index].Style.BackColor = conturiDGV.Rows[dc.Index].DefaultCellStyle.BackColor;

                    }
                }
            }
        }

        private void Setup()
        {

            SqlConnection wConn = DeschideConexiune(workConnString);
            Object ret = GetSetupValue("BalconSetup", "SoldPrecedentActiv", ModuleInfo.CodUnitate, wConn);
            Boolean val = false;
            if (ret == null || ret == DBNull.Value)
            {
                while (ret == null)
                {
                    /*MessageBox.Show("Modulul Balante Contabile nu a fost configurat. \nVa rugam sa-l configurati!",
                            "Eroare",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Hand);
                    ///configurare modul
                    #region Configurare Modul BalCon
                    FrmMainMdi frm = MdiParent as FrmMainMdi;
                    Assembly asm = frm.GetModule("erpforms");
                    if (asm == null)
                        return;
                    String numeClasa = "ERPForms.BalconSetupFrm";
                    Type mModule = asm.GetType(numeClasa);

                    if (mModule != null)
                    {
                        FrmCard newFrm = asm.CreateInstance(numeClasa, true, BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance, null,
                           new object[] { _moduleInfo }, Thread.CurrentThread.CurrentCulture, new object[] { }) as FrmCard;

                        newFrm.ShowDialog();
                    }
                    #endregion
                    ///configurare modul-----------------------------------
                     */
                    SqlCommand comcfg = new SqlCommand("INSERT INTO BalconSetup (CodUnitate,AnCurent,LunaCurenta) VALUES (" + ModuleInfo.CodUnitate.ToString() + "," + DateTime.Now.Year.ToString() + "," + DateTime.Now.AddMonths(-1).Month.ToString() + ")",
                         wConn);
                    comcfg.ExecuteNonQuery();
                    ret = GetSetupValue("BalconSetup", "SoldPrecedentActiv", ModuleInfo.CodUnitate, wConn);
                }

            }
            val = (Boolean)ret;
            DebitPrecedentColumn.Visible = val;
            CreditPrecedentColumn.Visible = val;
            if (!val)
            { 
                ///daca nu sunt afisate soldurile precedente facem fereastra mai mica
                ///
                this.Width -= 130;
            }
            InchideConexiune(wConn);
        }
        private Boolean GetSum(ref Decimal sumaDeb,ref Decimal sumaCre)
        { 
            sumaDeb = Decimal.Zero;
            sumaCre = Decimal.Zero;
             return true ;
        }

        private void conturiDGV_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            ///headerul gridului
            if (e.RowIndex == -1)
                return;
            //neinitializat gridul
            if ((conturiDGV.Columns["DebitInitialColumn"] == null) || (conturiDGV.Columns["CreditInitialColumn"] == null))
                return;
            
            if (e.ColumnIndex == conturiDGV.Columns["DebitInitialColumn"].Index ||
                (e.ColumnIndex == conturiDGV.Columns["CreditInitialColumn"].Index))
            {
                //CalculateSum();
            }
            if (e.ColumnIndex == TipContColumn.Index && e.RowIndex>=0)
            { 
                ///se modifica tipul contului
                ///
                String tip = conturiDGV[e.ColumnIndex, e.RowIndex].Value.ToString();
                if (tip == "A")
                {
                    conturiDGV[DebitInitialColumn.Index, e.RowIndex].ReadOnly = false;
                    conturiDGV[CreditInitialColumn.Index, e.RowIndex].ReadOnly = true;
                    conturiDGV[DebitInitialColumn.Index, e.RowIndex].Style.BackColor = conturiDGV.Rows[e.RowIndex].DefaultCellStyle.BackColor;
                    conturiDGV[CreditInitialColumn.Index, e.RowIndex].Style.BackColor = Color.LightGray;

                }
                if (tip == "P")
                {
                    conturiDGV[DebitInitialColumn.Index, e.RowIndex].ReadOnly = true;
                    conturiDGV[CreditInitialColumn.Index, e.RowIndex].ReadOnly = false;
                    conturiDGV[CreditInitialColumn.Index, e.RowIndex].Style.BackColor = conturiDGV.Rows[e.RowIndex].DefaultCellStyle.BackColor;
                    conturiDGV[DebitInitialColumn.Index, e.RowIndex].Style.BackColor = Color.LightGray;
                }
                if (tip == "B")
                {
                    conturiDGV[DebitInitialColumn.Index, e.RowIndex].ReadOnly = false;
                    conturiDGV[CreditInitialColumn.Index, e.RowIndex].ReadOnly = false;
                    conturiDGV[CreditInitialColumn.Index, e.RowIndex].Style.BackColor = conturiDGV.Rows[e.RowIndex].DefaultCellStyle.BackColor;
                    conturiDGV[DebitInitialColumn.Index, e.RowIndex].Style.BackColor = conturiDGV.Rows[e.RowIndex].DefaultCellStyle.BackColor;
                }
                conturiDGV[DebitInitialColumn.Index, e.RowIndex].Value = 0;
                conturiDGV[CreditInitialColumn.Index, e.RowIndex].Value = 0;

            }

        }
        override public void Salvare(object sender, EventArgs args)
        {
            String contCur = String.Empty;
            if (arhConturiBindingSource.Current != null)
            {
                ArhESRPDataSet.arhConturiRow cr = ((DataRowView)arhConturiBindingSource.Current).Row as ArhESRPDataSet.arhConturiRow;
                if (cr != null)
                    contCur = cr.Cont;
            }
            base.Salvare(this, args);

            if (EroareSalvare && args!=null)
            {
                SqlConnection con = DeschideConexiune(workConnString);
                try
                {
                    arhConturiTableAdapter.Connection = con;
                    ///nu schimba afisarile
                    ///

                    if (ModuleInfo.CurrentTheme != "tribunal")
                    {
                        if (listTSButton[idxBAfiseaza].Text != "Afiseaza toate conturile!")
                            arhConturiTableAdapter.FillByCategorieContParinte(arhESRPDataSet.arhConturi, ModuleInfo.CodUnitate,Convert.ToInt16(ModuleInfo.AnArhiva), ((byte)categorie), ContParinte.Peek(), FiltruDenumire);
                        else
                            arhConturiTableAdapter.FillUsedCategorie(arhESRPDataSet.arhConturi, FiltruDenumire, "N/A", ((byte)categorie), ModuleInfo.CodUnitate, Convert.ToInt16(ModuleInfo.AnArhiva));                        
                    }
                    
                }
               
                catch (System.Exception ex)
                {
                    System.Windows.Forms.MessageBox.Show(ex.Message);
                }
                finally
                {
                    InchideConexiune(con);
                }
            }

            #region Lansare thread actualizare
            if (NoRecUpdated > 0)
            {
                //Thread newThread = new Thread(ConturiRezumatFrm.UpdateSoldCont);
                //newThread.Start(new InfoThr(workConnString,ModuleInfo.CodUnitate));
            }

            #endregion
            if (contCur != String.Empty)
            {
                int poz = conturiBindingSource.Find("Cont", contCur);
                if (poz != -1)
                    conturiBindingSource.Position = poz;
            }
        }

        public struct InfoThr
        {
            public String ConnStr;
            public Int16 CodUnitate;
            public InfoThr(String cStr, Int16 _CodUnitate)
            {
                ConnStr = cStr;
                CodUnitate = _CodUnitate;
            }
        }


        private static void UpdateSoldCont(object info)
        {
            SqlCommand cmd = new SqlCommand("", DeschideConexiune(((InfoThr)info).ConnStr));
            cmd.CommandText = "balcon_UpdateSoldCont";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add(new SqlParameter("codUnitate", ((InfoThr)info).CodUnitate));
            cmd.ExecuteNonQuery();
            InchideConexiune(cmd.Connection);
        }


        /// <summary>
        /// avanseaza un nivel in planuri de conturi
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void conturiDGV_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            //daca ne aflam pe un nivel virtual nu mai avansam
            if (nivelVirtual || e.RowIndex<0)
                return;

            
            typeCont = conturiDGV.Rows[e.RowIndex].Cells["TipContColumn"].Value.ToString();
            if (typeCont != String.Empty)
                conturiDGV.Columns["TipContColumn"].ReadOnly = true;
            ContParinte.Push(conturiDGV.Rows[e.RowIndex].Cells["ContColumn"].Value.ToString());
            m_RanduriAnteriore.Push(conturiDGV.Rows[e.RowIndex]);
            
            Salvare(this, null);
            if (EroareSalvare)
                return;
            SqlConnection con = DeschideConexiune(workConnString);
            arhConturiTableAdapter.Connection = con;
            if (ModuleInfo.CurrentTheme != "tribunal")
            {
                if (listTSButton[idxBAfiseaza].Text != "Afiseaza toate conturile!")
                {

                    arhConturiTableAdapter.FillByCategorieContParinte(arhESRPDataSet.arhConturi, ModuleInfo.CodUnitate,Convert.ToInt16(ModuleInfo.AnArhiva), ((byte)categorie), ContParinte.Peek(), FiltruDenumire);
                }
                else
                {
                    // cele pe care se lucreaza
                    arhConturiTableAdapter.FillUsedCategorie(arhESRPDataSet.arhConturi, FiltruDenumire, ContParinte.Peek(), ((byte)categorie), ModuleInfo.CodUnitate, Convert.ToInt16(ModuleInfo.AnArhiva));
                }
            }
            else
                arhConturiTableAdapter.FillUsedCategorie(arhESRPDataSet.arhConturi, FiltruDenumire, ContParinte.Peek(), ((byte)categorie), ModuleInfo.CodUnitate, Convert.ToInt16(ModuleInfo.AnArhiva));

            InchideConexiune(con);
            conturiBindingSource.Sort = "[SortValue]";
            nivelVirtual = conturiBindingSource.Count == 0;
            SetStatusNavigationButtons();

            #region Setari valori implicite
            arhESRPDataSet.arhConturi.CategorieColumn.DefaultValue = categorie;
            if (typeCont != String.Empty)
                arhESRPDataSet.arhConturi.TipColumn.DefaultValue = typeCont;
            if (ContParinte.Peek() != "N/A")
                arhESRPDataSet.arhConturi.ContColumn.DefaultValue = ContParinte.Peek() + ".";
            arhESRPDataSet.arhConturi.ContParinteColumn.DefaultValue = ContParinte.Peek();
            #endregion
        }
        /// <summary>
        /// revine la nivelul anterior de conturi
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RevenireNivelAnterior(object sender, EventArgs e)
        {
            //scoate contul din varful stivei pentu selectie
            /// daca stiva e goala nu face nimic
            if (ContParinte.Count == 0)
                return;
            
            Salvare(this, null);
            if (EroareSalvare)
                return;
            String contAnt = ContParinte.Pop();
            SqlConnection con = DeschideConexiune(workConnString);
            try
            {
                
                arhConturiTableAdapter.Connection = con;
                this.tipContTableAdapter.Connection = con;
                this.tipContTableAdapter.Fill(this.eSRPDataSet.TipCont);
                if (listTSButton[idxBAfiseaza].Text != "Afiseaza toate conturile!")
                {
                    //// toate la gramada
                    arhConturiTableAdapter.FillByCategorieContParinte(arhESRPDataSet.arhConturi, ModuleInfo.CodUnitate,Convert.ToInt16(ModuleInfo.AnArhiva), ((byte)categorie), ContParinte.Peek(), FiltruDenumire);
                }
                else
                {
                    // cele pe care se lucreaza
                    arhConturiTableAdapter.FillUsedCategorie(arhESRPDataSet.arhConturi, FiltruDenumire, ContParinte.Peek(), ((byte)categorie), ModuleInfo.CodUnitate, Convert.ToInt16(ModuleInfo.AnArhiva));
                }

            }
            catch (System.Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
                return;
            }
            finally
            {
                InchideConexiune(con);
            }

            nivelVirtual = conturiBindingSource.Count == 0;
            SetStatusNavigationButtons();

            /// selecteaza nodul bunic
            ///
            DataGridViewRow dr = m_RanduriAnteriore.Pop();
            int rdSel = conturiBindingSource.Find("Cont", contAnt);
            conturiBindingSource.Position = rdSel;
            
            if (ContParinte.Peek() == "N/A")
            {
                typeCont = String.Empty;
                conturiDGV.Columns["TipContColumn"].ReadOnly = false;
                conturiBindingSource.Sort = "[SortValue]";
            }

            #region Setari valori implicite
            arhESRPDataSet.arhConturi.CategorieColumn.DefaultValue = categorie;
            if (typeCont != String.Empty)
                arhESRPDataSet.arhConturi.TipColumn.DefaultValue = typeCont;
            if (ContParinte.Peek() != "N/A")
                arhESRPDataSet.arhConturi.ContColumn.DefaultValue = ContParinte.Peek() + ".";
            arhESRPDataSet.arhConturi.ContParinteColumn.DefaultValue = ContParinte.Peek(); 
            #endregion
            
            
        }

        private void SetStatusNavigationButtons()
        {
            if (idxBAnterior == -1 || idxBUrmator == -1)
                return;
            if (ContParinte.Peek() == "N/A")
            {
                listTSButton[idxBAnterior].Enabled = false;
                listTSButton[idxBUrmator].Enabled = true;
                this.Text = "Rezumat Conturi";
            }
            else
            {
                if (!nivelVirtual)
                {
                    listTSButton[idxBAnterior].Enabled = true;
                    listTSButton[idxBUrmator].Enabled = true;
                }
                else
                {
                    listTSButton[idxBAnterior].Enabled = true;
                    listTSButton[idxBUrmator].Enabled = false;                
                }
                this.Text = "Rezumat Conturi - " + ContParinte.Peek();
            }                
        }

        private void tSBNext_Click(object sender, EventArgs e)
        {
            if(conturiDGV.SelectedCells.Count == 0){
                MessageBox.Show("Va rugam selectati un cont!", "Atentie");
                return;
            }
            conturiDGV_CellDoubleClick(conturiDGV,
                new DataGridViewCellEventArgs(1, conturiDGV.SelectedCells[0].RowIndex));
        }

        private void bilantToolStripMenuItem_Click(object sender, EventArgs e)
        {
            categorie = 0;
            AfiseazaConturiUtilizate(this, null);
        }

        private void inAfaraBilantuluiToolStripMenuItem_Click(object sender, EventArgs e)
        {
            categorie = 2;
            AfiseazaConturiUtilizate(this, null);
        }

        private void ProprietatiConturi(object sender, EventArgs e)
        {
            if (conturiDGV.SelectedCells.Count == 0)
            {
                MessageBox.Show("Va rugam selectati un cont!", "Atentie");
                return;
            }
            int SavePos = conturiBindingSource.Position;
            ConturiSpecialeFrm frm = new ConturiSpecialeFrm(conturiDGV.Rows[conturiDGV.SelectedCells[0].RowIndex].Cells["ContColumn"].Value.ToString(),
                conturiDGV[ContParinteColumn.Index, conturiDGV.SelectedCells[0].RowIndex].Value.ToString(),
                Convert.ToByte(conturiDGV[CategorieColumn.Index, conturiDGV.SelectedCells[0].RowIndex].Value),
                Convert.ToBoolean(conturiDGV[TerminalColumn.Index, conturiDGV.SelectedCells[0].RowIndex].Value),
                Convert.ToBoolean(conturiDGV[esteAnaliticColumn.Index, conturiDGV.SelectedCells[0].RowIndex].Value),
                ModuleInfo);
            frm.ShowDialog();
            if (frm.MustRefresh)
            {
                AfiseazaConturiUtilizate(this, null);
                conturiBindingSource.Position = SavePos;
            }
        }

        override public void SetCurentUnit(short vCodUnitate)
        {
            ModuleInfo.CodUnitate = vCodUnitate;
            AfiseazaConturiUtilizate(this, null);
        }

        private void conturiDGV_CellValidated(object sender, DataGridViewCellEventArgs e)
        {
            /// valideaza soldurile initiale pentru conturile bifunctionale
            /// 
            String tip = conturiDGV[TipContColumn.Index, e.RowIndex].Value.ToString();
            if (tip == "B")
            {
                Decimal sid = Convert.ToDecimal(conturiDGV[DebitInitialColumn.Index, e.RowIndex].Value);
                Decimal sic = Convert.ToDecimal(conturiDGV[CreditInitialColumn.Index, e.RowIndex].Value);
                if (sid != Decimal.Zero && sic != Decimal.Zero)
                {
                    MessageBox.Show("Soldul initial al contului " + conturiDGV[ContColumn.Index, e.RowIndex].Value.ToString()
                        + " poate fi pe debit sau pe credit. \nVa rugam sa corectati eroarea!\nPentru anularea modificarilor apasati tasta ESCAPE!",
                            "Eroare",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Hand);
                    //e.Cancel = true;
                    //conturiDGV[CreditInitialColumn.Index, e.RowIndex].Selected = true;
                }
            }
        }

        override public void SetCurentMonth(short vCodUnitate)
        {
            //Setup(conn);
        }
        /// <summary>
        /// cand se apasa enter, controlul activ este luna, anul
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        override public void toolStripLabelAnLuna_Click(object sender, EventArgs e)
        {

        }

        private void NoteContabile(object sender, EventArgs e)
        { 
             if(conturiDGV.SelectedCells.Count == 0){
                MessageBox.Show("Va rugam selectati un cont!", "Atentie");
                return;
            }
             conturiDGV_CellContentClick(sender, new DataGridViewCellEventArgs(SoldColumn.Index, conturiDGV.SelectedCells[0].RowIndex));
        }

        private void conturiDGV_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == SoldColumn.Index)
            {
                NoteContabileRezumatFrm _frmNCR = new NoteContabileRezumatFrm(null,ModuleInfo);
                _frmNCR.MdiParent = this.MdiParent;
                _frmNCR.SelectionAddOn = true;
                _frmNCR.filtruNote = conturiDGV.SelectedRows[0].Cells["ContColumn"].Value.ToString();
                _frmNCR.Show();

                
            }
        }


        #region Events Tribunal
        private void inAfaraBilantuluiTribunal_Click(object sender, EventArgs e)
        {
            categorie = 2;
            Salvare(this, null);
            if (EroareSalvare)
                return;

            try
            {
                SqlConnection con = DeschideConexiune(workConnString);
                this.tipContTableAdapter.Connection = con;
                this.tipContTableAdapter.Fill(this.eSRPDataSet.TipCont);
                //tribunal
                AfiseazaToateConturile(con, true, false);
                InchideConexiune(con);
            }
            catch (System.Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
            }
        }

        private void bilantTribunal_Click(object sender, EventArgs e)
        {
            categorie = 0;
            Salvare(this, null);
            if (EroareSalvare)
                return;

            try
            {
                SqlConnection con = DeschideConexiune(workConnString);
                this.tipContTableAdapter.Connection = con;
                this.tipContTableAdapter.Fill(this.eSRPDataSet.TipCont);
                //tribunal
                AfiseazaToateConturile(con, true, false);
                InchideConexiune(con);
            }
            catch (System.Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
            }
        }

        private void conturiDGV_CellDoubleClickTribunal(object sender, EventArgs e)
        {

            if (conturiDGV.SelectedCells.Count == 0)
            {
                MessageBox.Show("Va rugam selectati un cont!", "Atentie");
                return;
            }


            int RowIndex = conturiDGV.SelectedCells[0].RowIndex;
            //daca ne aflam pe un nivel virtual nu mai avansam
            if (nivelVirtual || RowIndex < 0)
                return;


            typeCont = conturiDGV.Rows[RowIndex].Cells["TipContColumn"].Value.ToString();
            if (typeCont != String.Empty)
                conturiDGV.Columns["TipContColumn"].ReadOnly = true;
            ContParinte.Push(conturiDGV.Rows[RowIndex].Cells["ContColumn"].Value.ToString());
            m_RanduriAnteriore.Push(conturiDGV.Rows[RowIndex]);

            Salvare(this, null);
            if (EroareSalvare)
                return;
            SqlConnection con = DeschideConexiune(ModuleInfo.workConnectionString);
            arhConturiTableAdapter.Connection = con;
            arhConturiTableAdapter.FillByCategorieContParinte(arhESRPDataSet.arhConturi, ModuleInfo.CodUnitate, Convert.ToInt16(ModuleInfo.AnArhiva), ((byte)categorie), ContParinte.Peek(), FiltruDenumire);

            InchideConexiune(con);
            conturiBindingSource.Sort = "[SortValue]";
            nivelVirtual = conturiBindingSource.Count == 0;
            SetStatusNavigationButtons();

            #region Setari valori implicite
            arhESRPDataSet.arhConturi.CategorieColumn.DefaultValue = categorie;
            if (typeCont != String.Empty)
                arhESRPDataSet.arhConturi.TipColumn.DefaultValue = typeCont;
            if (ContParinte.Peek() != "N/A")
                arhESRPDataSet.arhConturi.ContColumn.DefaultValue = ContParinte.Peek() + ".";
            arhESRPDataSet.arhConturi.ContParinteColumn.DefaultValue = ContParinte.Peek();
            #endregion
        }


        /// <summary>
        /// revine la nivelul anterior de conturi
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RevenireNivelAnteriorTribunal(object sender, EventArgs e)
        {
            //scoate contul din varful stivei pentu selectie
            /// daca stiva e goala nu face nimic
            if (ContParinte.Count == 0)
                return;

            Salvare(this, null);
            if (EroareSalvare)
                return;
            String contAnt = ContParinte.Pop();
            SqlConnection con = DeschideConexiune(workConnString);
            try
            {
                
                arhConturiTableAdapter.Connection = con;
                this.tipContTableAdapter.Connection = con;
                this.tipContTableAdapter.Fill(this.eSRPDataSet.TipCont);
                arhConturiTableAdapter.FillByCategorieContParinte(arhESRPDataSet.arhConturi, ModuleInfo.CodUnitate,Convert.ToInt16(ModuleInfo.AnArhiva), ((byte)categorie), ContParinte.Peek(), FiltruDenumire);

            }
            catch (System.Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
                return;
            }
            finally
            {
                InchideConexiune(con);
            }

            nivelVirtual = conturiBindingSource.Count == 0;
            SetStatusNavigationButtons();

            /// selecteaza nodul bunic
            ///
            DataGridViewRow dr = m_RanduriAnteriore.Pop();
            int rdSel = conturiBindingSource.Find("Cont", contAnt);
            conturiBindingSource.Position = rdSel;

            if (ContParinte.Peek() == "N/A")
            {
                typeCont = String.Empty;
                conturiDGV.Columns["TipContColumn"].ReadOnly = false;
                conturiBindingSource.Sort = "[SortValue]";
            }

            #region Setari valori implicite
            arhESRPDataSet.arhConturi.CategorieColumn.DefaultValue = categorie;
            if (typeCont != String.Empty)
                arhESRPDataSet.arhConturi.TipColumn.DefaultValue = typeCont;
            if (ContParinte.Peek() != "N/A")
                arhESRPDataSet.arhConturi.ContColumn.DefaultValue = ContParinte.Peek() + ".";
            arhESRPDataSet.arhConturi.ContParinteColumn.DefaultValue = ContParinte.Peek();
            #endregion


        }
        #endregion


        bool DocumenteFrm_HandleBeforeDelAfterMessage(object sender, EventArgs args, Boolean dingrid)
        {
            foreach (DataRowView dl in conturiCorespBindingSource)
                conturiCorespBindingSource.Remove(dl);
            foreach (DataRowView dl in conturiCorespBindingSource1)
                conturiCorespBindingSource1.Remove(dl);
            foreach (DataRowView dl in conturiSpecialeBindingSource)
                conturiSpecialeBindingSource.Remove(dl);
            return true;
        }

       

    }


}
